package com.yekong.house.biz.service.impl;

import com.yekong.house.biz.mapper.AgencyMapper;
import com.yekong.house.biz.service.AgencyService;
import com.yekong.house.common.model.Agency;
import com.yekong.house.common.model.User;
import com.yekong.house.common.page.PageData;
import com.yekong.house.common.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AgencyServiceImpl implements AgencyService {
/*    @Autowired
    private UserService userService;*/

    @Autowired
    private AgencyMapper agencyMapper;

    @Value("${file.prefix}")
    private String imgPrefix;

    /**
     *  访问 user 表获取详情
     *  添加用户头像
    @Override     */

    public User getAgentDetail(Long userId) {
        User user = new User();
        user.setId(userId);
        user.setType(2);
        List<User> users = agencyMapper.selectAgent(user,PageParams.build(1,1));
        setImg(users);
        if(!users.isEmpty()){
            User agent = users.get(0);
            // 将经纪人关联的经纪机构一并查询出来
            Agency agency = new Agency();
            agency.setId(agent.getAgencyId().intValue());
            List<Agency> agencies = agencyMapper.select(agency);
            if (!agencies.isEmpty()) {
                agent.setAgencyName(agencies.get(0).getName());
            }
            return agent;
        }
        return null;
    }

    @Override
    public PageData<User> getAllAgent(PageParams pageParams) {
        List<User> agents =  agencyMapper.selectAgent(new User(),pageParams);
        setImg(agents);
        Long count = agencyMapper.selectAgentCount(new User());
        return PageData.buildPage(agents, count, 2, pageParams.getPageNum());
    }

    private void setImg(List<User> users) {
        users.forEach(i ->{
            i.setAvatar(imgPrefix+i.getAvatar());
        });
    }

    @Override
    public List<Agency> getAllAgency() {
        return agencyMapper.select(new Agency());
    }

    @Override
    public Agency getAgency(Integer id) {
        Agency agency = new Agency();
        agency.setId(id);
        List<Agency> agencies = agencyMapper.select(agency);
        if (agencies.isEmpty()) {
            return null;
        }
        return agencies.get(0);
    }

    @Override
    public int add(Agency agency) {
        return  agencyMapper.insert(agency);
    }


}
